package edu.ubb.scrumster.model.repository;

import java.util.ArrayList;
import java.util.List;

import edu.ubb.scrumster.model.model.AbstractModel;
import edu.ubb.scrumster.model.model.Organization;
import edu.ubb.scrumster.model.model.Scrum;
import edu.ubb.scrumster.model.model.User;

public class UserRepository {

	public UserRepository() {
	}

	public ArrayList<User> getAllUser() {
		ArrayList<User> list = new ArrayList<User>();
		for (AbstractModel d : DatabaseAccess.getInstance().getAll(DatabaseAccess.USER)) {
			list.add(getUserById(((User) d).getId()));
		}
		return list;
	}

	public void addUser(User g) {
		DatabaseAccess.getInstance().addData(g);
	}

	public void updateUser(User data) {
		DatabaseAccess.getInstance().updateData(data);
	}

	public void deleteUser(User data) {
		DatabaseAccess.getInstance().deleteData(data);
	}

	public User getUserById(int id) {
		User u = (User) DatabaseAccess.getInstance().getDataById(id, DatabaseAccess.USER);
		int scrumId;
		if (u.getScrum() != null) {
			scrumId = u.getScrum().getId();
			u.setScrum((Scrum) DatabaseAccess.getInstance().getDataById(scrumId,
					DatabaseAccess.SCRUM));
		}
		if (u.getOrganization() != null)
			u.setOrganization((Organization) DatabaseAccess.getInstance()
					.getDataById(u.getOrganization().getId(),
							DatabaseAccess.ORGANIZATION));
		return u;
	}

	public User login(String username, String password) {
		User u = (User) DatabaseAccess.getInstance().login(username, password);
		if (u != null) {
			if (u.getScrum() != null) {
				u.setScrum((Scrum) DatabaseAccess.getInstance().getDataById(
						u.getScrum().getId(), DatabaseAccess.SCRUM));
			}
			if (u.getOrganization() != null)
				u.setOrganization((Organization) DatabaseAccess.getInstance()
						.getDataById(u.getOrganization().getId(),
								DatabaseAccess.ORGANIZATION));
		}
		return u;
	}

	public List<User> getUserByScrum(int id) {
		ArrayList<User> list = new ArrayList<User>();
		for (AbstractModel d : DatabaseAccess.getInstance().getUserByScrum(id)) {
			list.add(getUserById(((User) d).getId()));
		}
		return list;
	}
}
